package com.open.api.wechat.utils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author : zhaoxuan
 * @date : 2021/6/24 21:35
 * @description : http工具类
 * @version : 1.0
 */
@Slf4j
public class HttpUtil {

    /**
     * 线程池
     */
    private static final ConnectionPool CONNECTION_POOL = new ConnectionPool();

    /**
     * 超时时间
     */
    private static final int TIME_OUT = 60;

    /**
     * 请求MIME类型
     */
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    /**
     * 单例的OkHttpClient
     */
    private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder()
            .addInterceptor(new LoggingInterceptor())
            .callTimeout(TIME_OUT, TimeUnit.SECONDS)
            .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
            .readTimeout(TIME_OUT, TimeUnit.SECONDS)
            .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
            .connectionPool(CONNECTION_POOL)
            .build();

    /**
     * @author : zhaoxuan
     * @date : 2021/6/24 22:19
     * @description : OkHttpClient拦截器
     * @version : 1.0
     */
    @Slf4j
    private static class LoggingInterceptor implements Interceptor {

        @NotNull
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            long t1 = System.nanoTime();
            log.info("Sending request {}",request.url());

            Response response = chain.proceed(request);

            long t2 = System.nanoTime();
            log.info("Received response for {} in {}",response.request().url(), (t2 - t1) / 1e6d);
            return response;
        }
    }

    /**
     * @author  zhaoxuan
     * @date  2021/6/24 22:28
     * @params  [url]
     * @return  java.lang.String
     * @description get请求
     */
    public static String get(String url) {
        Request request = new Request.Builder().url(url).build();
        try (Response response = OK_HTTP_CLIENT.newCall(request).execute()) {
            return response.body().string();
        } catch (IOException e) {
            log.error("Failed sending request, url: {}", request.url(), e);
        }
        return "";
    }

    /**
     * @author  zhaoxuan
     * @date  2021/6/24 22:29
     * @params  [url, body]
     * @return  java.lang.String
     * @description POST JSON 请求
     */
    public static String post(String url, String body) {
        RequestBody requestBody = RequestBody.create(JSON, body);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        try (Response response = OK_HTTP_CLIENT.newCall(request).execute()) {
            return response.body().string();
        } catch (IOException e) {
            log.error("Failed sending request, url: {}, body: {}", request.url(), body, e);
        }
        return "";
    }

    /**
     * @author  zhaoxuan
     * @date  2021/6/24 22:29
     * @params  [url, body]
     * @return  java.lang.String
     * @description 定制化   用于请求图片
     */
    public static Response getFile(String url) {
        Request request = new Request.Builder().url(url).build();
        try {
            return OK_HTTP_CLIENT.newCall(request).execute();
        } catch (IOException e) {
            log.error("Failed sending request, url: {}", request.url(), e);
        }
        return null;
    }

    /**
     * @author  zhaoxuan
     * @date  2021/6/24 22:29
     * @params  [url, body]
     * @return  java.lang.String
     * @description 定制化   用于请求图片
     */
    public static Response postFile(String url, String body) {
        RequestBody requestBody = RequestBody.create(JSON, body);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        try{
            return OK_HTTP_CLIENT.newCall(request).execute();
        } catch (IOException e) {
            log.error("Failed sending request, url: {}, body: {}", request.url(), body, e);
        }
        return null;
    }
}
